package com.veer.shop.service.impl.admin;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.veer.shop.config.Constants;
import com.veer.shop.mapper.ProductCategoryMapper;
import com.veer.shop.pojo.ProductCategory;
import com.veer.shop.pojo.ResponseData;
import com.veer.shop.service.admin.CategoryService;
import com.veer.shop.utils.DateTimeUtil;
import com.veer.shop.utils.ResponseUtil;

@Service
public class CategoryServiceImpl implements CategoryService{
	
	@Autowired
	private ProductCategoryMapper productCategoryMapper;
	
	/**
	 * 获取所有分类
	 */
	@Override
	public ResponseData<?> getAll() {
		// 查询所有的分类
		List<Map<String, Object>> categories = productCategoryMapper.selectAll();
		
		List<Map<String, Object>> newCategory = new ArrayList<>();
		
		for(Map<String, Object> category : categories)
		{
			if(category.get("parent_id").toString().equals("0")) {
				newCategory.add(category);
			}
		}
		
		for(Map<String, Object> category : newCategory)
		{
			List<Map<String, Object>> cList = getCategoryTree(category.get("category_id").toString(), categories);
			
			if(cList.size()>0) {
				category.put("items", cList);
			}
		}
		
		return ResponseUtil.success(newCategory.get(0));
	}
	
	/**
	 * 获取分类树形结构
	 * 
	 * @param categories
	 * @return
	 */
	private List<Map<String, Object>> getCategoryTree(String parentId, List<Map<String, Object>> categories) {
		
		List<Map<String, Object>> childList = new ArrayList<Map<String, Object>>();
		
		for(Map<String, Object> category : categories)
		{
			if(category.get("parent_id").toString().equals(parentId)) {
				childList.add(category);
			}
		}
		
		//递归
		for (Map<String, Object> category : childList) {
			List<Map<String, Object>> cList = getCategoryTree(category.get("category_id").toString(), categories);
			if(cList.size()>0) {
				category.put("items", cList);
			}
		}
		
		//如果节点下没有子节点，返回一个空List（递归退出）
		if(childList.size() == 0) {
			return new ArrayList<Map<String, Object>>();
		}
		
		return childList;
	}
	
	/**
	 * 批量删除分类
	 */
	@Override
	public ResponseData<?> delete(String categoryIds) {
		// TODO Auto-generated method stub
		if(categoryIds.equals("")) {
			return ResponseUtil.error("分类ID为空！");
		}
		
		// 字符串转化为 list
		String[] categoryIdList = categoryIds.split(Constants.SEPARATOR_STRING);
		
		for(String categoryId : categoryIdList)
		{
			// 默认系统根分类不可删除
			if(Integer.parseInt(categoryId) == Constants.DEFAULT_PRODUCT_CATEGORY_ID)continue;
			
			productCategoryMapper.delete(categoryId);
		}
		
		return ResponseUtil.success();
	}
	
	@Override
	public ResponseData<?> get(int categoryId) {
		// TODO Auto-generated method stub
		ProductCategory category = productCategoryMapper.selectById(categoryId);
		
		if(category == null) {
			return ResponseUtil.error("分类不存在！");
		}
		
		return ResponseUtil.success(category);
	}
	
	/**
	 * 新增和更新分类
	 */
	@Override
	public ResponseData<?> update(ProductCategory category) {
		// TODO Auto-generated method stub
		int count = 0;
		
		// 参数校验
		Map<String, String> valid = validCategory(category);
		
		if(valid.get("code").equals("-1")) {
			return ResponseUtil.error(valid.get("message"));
		}
		
		// 根据父分类ID查询父分类信息
		ProductCategory parentCategory = productCategoryMapper.selectById(category.getParent_id());
		
		// 父分类不存在
		if(parentCategory.getName().equals("")) {
			return ResponseUtil.error("父分类不存在！");
		}
		
		// 根据父分类的层级和路径处理当前分类
		category.setLevel(parentCategory.getLevel()+1);
		
		if(String.valueOf(category.getCategoryId()).equals("0")) {
			
			category.setCreated_at(DateTimeUtil.getDateTime());
			category.setUpdated_at(category.getCreated_at());
			
			// 新增分类
			count = productCategoryMapper.insert(category);
			
			if(count > 0) {
				category.setPath(parentCategory.getPath() + '/' + category.getCategoryId());
				productCategoryMapper.update(category);
			}
		} else {
			
			category.setUpdated_at(DateTimeUtil.getDateTime());
			
			// 更新分类
			count = productCategoryMapper.update(category);
		}
		
		if(count > 0) {
			return ResponseUtil.success();
		} else {
			return ResponseUtil.error();
		}
	}
	
	/**
	 * 参数校验
	 * 
	 * @param category
	 * @return
	 */
	private Map<String, String> validCategory(ProductCategory category) {
		Map<String, String> result = new HashMap<String, String>();
		result.put("code", "-1");
		
		// 分类名称不可为空
		if(category.getName().equals("")) {
			result.put("message", "分类名称不可为空！");
			return result;
		}
		
		// 分类编码不可为空
		if(category.getCategory_bn().equals("")) {
			result.put("message", "分类编码不可为空！");
			return result;
		}
		
		// 父分类ID不可为空
		if(String.valueOf(category.getParent_id()).equals("")) {
			result.put("message", "父分类ID不可为空");
			return result;
		}
		
		List<Map<String, Object>> searchList = null;
		if(String.valueOf(category.getCategoryId()).equals("0")) {
			// 新增分类时，校验分类名和分类编码是否已存在
			searchList = productCategoryMapper.search(category.getName(), null, 0);
			if(searchList.size() > 0) {
				result.put("message", "分类名称已存在！");
				return result;
			}
			
			searchList = productCategoryMapper.search(null, category.getCategory_bn(), 0);
			if(searchList.size() > 0) {
				result.put("message", "分类编码已存在！");
				return result;
			}
		} else {
			// 更新分类时，校验分类名和分类编码是否已存在
			searchList = productCategoryMapper.search(category.getName(), null, category.getCategoryId());
			if(searchList.size() > 0) {
				result.put("message", "分类名称已存在！");
				return result;
			}
			
			searchList = productCategoryMapper.search(null, category.getCategory_bn(), category.getCategoryId());
			if(searchList.size() > 0) {
				result.put("message", "分类编码已存在！");
				return result;
			}
		}
		
		result.put("code", "0");
		
		return result;
	}
}
